import React, { ReactNode, Component, Fragment } from 'react';
import { Form, Select, DatePicker, Input, Button, Table } from 'antd';
import moment from 'moment';
import { connect } from 'dva';
// eslint-disable-next-line import/no-extraneous-dependencies
import { withRouter } from 'react-router-dom';

import { handleSendData, initialTimeWithMill } from '@/utils/tools';
import { getMemberList } from './service';
import { SEARCH_TYPE, PAGINATION_OPTION, SUCCESS_CODE } from './data';
import { StateType, getMemberColumns } from './utils';
import styles from './style.less';

import DetailDialog from './components/detailDialog';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { Option } = Select;

class Search extends Component<StateType> {
  public state = {
    tableData: {
      list: [],
      total: 0,
    },
    page: 1,
    size: 20,
    loading: false,
    detailVisible: false,
    rowData: {},
  };

  componentDidMount() {
    this.getTableData();
  }

  getTableData = () => {
    this.props.form.validateFieldsAndScroll((err: any, values: any) => {
      if (!err) {
        this.setState({ loading: true });
        const { page, size } = this.state;
        const params = handleSendData(values, 'startDate', 'endDate');
        getMemberList({ ...params, page, size }).then(res => {
          if (res) {
            const { code, data } = res;
            if (code === SUCCESS_CODE && data) {
              this.setState({ tableData: data, loading: false });
            }
          }
        });
      }
    });
  };

  // 搜索
  handleSubmit = (e: any) => {
    e.preventDefault();
    this.setState({ page: 1 }, () => {
      this.getTableData();
    });
  };

  // 重置
  handleReset = () => {
    this.setState({ page: 1 }, () => {
      this.props.form.resetFields();
      this.getTableData();
    });
  };

  onTableChange = (pagination: any) => {
    const { current, pageSize } = pagination;
    this.setState({ page: current, size: pageSize }, () => {
      this.getTableData();
    });
  };

  showDetail = (rowData: any) => {
    this.setState({ detailVisible: true, rowData });
  };

  // 渲染表单
  renderForm = () => {
    const { getFieldDecorator } = this.props.form;

    return (
      <Form layout="inline" onSubmit={this.handleSubmit}>
        <FormItem label="注册时间">
          {getFieldDecorator('time', {
            initialValue: initialTimeWithMill(338),
          })(
            <RangePicker
              format="YYYY-MM-DD HH:mm:ss"
              placeholder={['开始时间', '结束时间']}
              showTime={{
                hideDisabledOptions: true,
                defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
              }}
            />,
          )}
        </FormItem>

        <FormItem style={{ marginRight: '5px' }}>
          {getFieldDecorator('searchType', {
            initialValue: SEARCH_TYPE['0'].value,
          })(
            <Select style={{ width: '120px' }}>
              {SEARCH_TYPE.map(item => (
                <Option key={item.value} value={item.value}>
                  {item.title}
                </Option>
              ))}
            </Select>,
          )}
        </FormItem>

        <FormItem>{getFieldDecorator('keywords')(<Input placeholder="" />)}</FormItem>

        <FormItem>
          {/* 查询 */}
          <Button type="primary" htmlType="submit">
            查询
          </Button>
          {/* 重置 */}
          <Button style={{ marginLeft: '10px' }} onClick={this.handleReset}>
            重置
          </Button>
        </FormItem>
      </Form>
    );
  };

  // 渲染表格
  renderTable = () => {
    const { tableData, page, size, loading } = this.state;
    const { total } = this.state.tableData;

    return (
      <Table
        className={styles.tableStyle}
        loading={loading}
        style={{ wordBreak: 'break-all', marginTop: '20px' }}
        columns={getMemberColumns(this.showDetail)}
        dataSource={tableData.list}
        scroll={{ y: 540 }}
        rowKey={(record: any, index: number) => String(index)}
        onChange={this.onTableChange}
        pagination={{
          total,
          pageSize: size,
          current: page,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: () => `共 ${total} 条记录， 第${page}/${Math.ceil(total / size)}`,
          pageSizeOptions: PAGINATION_OPTION,
        }}
      />
    );
  };

  render(): ReactNode {
    const { detailVisible, rowData } = this.state;

    return (
      <Fragment>
        {detailVisible ? (
          <DetailDialog<>
            data={rowData}
            close={() => {
              this.setState({ rowData: {}, detailVisible: false });
            }}
          />
        ) : (
          <div className={styles.searchWrapper}>
            {this.renderForm()}
            {this.renderTable()}
          </div>
        )}
      </Fragment>
    );
  }
}
const SearchWrapper = Form.create({ name: 'memberSearch' })(Search);
// export default SearchWrapper;

export default withRouter(
  connect(({ global }: { global: any }) => ({
    btns: global.btns,
  }))(SearchWrapper),
);
